import 'package:casdon/core/logger/log.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class CacheUtils {
  // ✅ 获取总缓存大小（MB）
  static Future<double> getCacheSizeMB() async {
    double totalSize = 0;

    // Android & iOS 缓存目录
    final tempDir = await getTemporaryDirectory();
    totalSize += await _calculateDirSize(tempDir);

    // Android 应用数据目录
    if (Platform.isAndroid) {
      final appSupportDir = await getApplicationSupportDirectory();
      totalSize += await _calculateDirSize(appSupportDir);
    }

    return totalSize / (1024 * 1024);
  }

  // ✅ 计算目录大小
  static Future<double> _calculateDirSize(Directory dir) async {
    try {
      if (!await dir.exists()) return 0;

      double size = 0;
      final files = dir.listSync(recursive: true);

      for (var file in files) {
        if (file is File) {
          size += file.lengthSync();
        }
      }
      return size;
    } catch (e) {
      Log.e('计算目录大小出错:', e, StackTrace.current);
      return 0;
    }
  }

  // ✅ 清空缓存
  static Future<void> clearCache() async {
    final tempDir = await getTemporaryDirectory();
    await _deleteDir(tempDir);

    if (Platform.isAndroid) {
      final appSupportDir = await getApplicationSupportDirectory();
      await _deleteDir(appSupportDir);
    }
  }

  static Future<void> _deleteDir(Directory dir) async {
    if (await dir.exists()) {
      await dir.delete(recursive: true);
    }
  }
}
